<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="searchData.type_id" class="filter-item" placeholder="请选择类型">
        <el-option
          v-for="item in typeOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="searchData.location" class="filter-item" placeholder="请选择位置">
        <el-option
          v-for="item in localOption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模块名称" align="center" width="350px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleOpenMap(row)">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标识" align="center" width="180px">
        <template slot-scope="{row}">
          <span>{{ row.sign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.type_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.location_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="80px">
        <template slot-scope="{row}">
          <el-tag v-if="row.status === 0" type="info">下架</el-tag>
          <el-tag v-if="row.status === 1" type="success">上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <router-link class="el-button el-button--success el-button--mini" :to="'config/list/' + row.id">配置<i class="el-icon-upload el-icon--right" /></router-link>
          <el-button v-if="row.status === 0" size="mini" type="danger" @click="handleStatus(row.id)">下架</el-button>
          <el-button v-if="row.status === 1" size="mini" type="danger" @click="handleStatus(row.id)">上架</el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗  -->
    <el-dialog title="创建/编辑模块" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="width: 800px; margin-left:50px;">
        <el-form-item label="中文名称" prop="cn_name">
          <el-input v-model="addData.cn_name" />
        </el-form-item>
        <el-form-item label="英文名称" prop="en_name">
          <el-input v-model="addData.en_name" />
        </el-form-item>
        <el-form-item label="标识" prop="sign">
          <el-input v-model="addData.sign" />
        </el-form-item>
        <el-form-item label="页面" prop="location">
          <el-select v-model="addData.location" class="filter-item" placeholder="请选择类型">
            <el-option
              v-for="item in localOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="景点类型" prop="type_id">
          <el-select v-model="addData.type_id" class="filter-item" placeholder="请选择类型">
            <el-option
              v-for="item in typeOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          删除
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { moduleList, moduleAdd, moduleDel } from '@/api/module'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import router from '../../router' // secondary package based on el-pagination

export default {
  name: 'ModuleList',
  components: { },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '待审核',
        '1': '已审核',
        '2': '已上架',
        '99': '已删除'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      currentItemId: 0,
      // 类型
      typeOption: [],
      localOption: [],
      config: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      searchData: {
        pageIndex: 1,
        pageSize: 15,
        location: 'all',
        type_id: 'all',
        status: 'all'
      },
      addData: {
        id: 0,
        cn_name: '',
        en_name: '',
        location: 'index',
        sign: '',
        type_id: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        type_id: [{ required: true, message: '类型需要选择', trigger: 'change' }],
        cn_name: [{ required: true, message: '需要填写中文名称', trigger: 'blur' }],
        en_name: [{ required: true, message: '需要填写英文名称', trigger: 'blur' }],
        location: [{ required: true, message: '需要选择位置', trigger: 'change' }],
        sign: [{ required: true, message: '需要填写标识', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      moduleList(this.searchData).then(response => {
        this.list = response.data.item
        this.typeOption = response.data.typeOption
        this.localOption = response.data.locationOption
        this.config = response.data.config

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.searchData.pageIndex = 1
      this.getList()
    },
    handleStatus(id) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
    },
    resetAddData() {
      this.addData = {
        id: 0,
        cn_name: '',
        en_name: '',
        location: 'index',
        sign: '',
        type_id: 1
      }
    },
    handleCreate() {
      this.resetAddData()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          moduleAdd(this.addData).then((response) => {
            console.log(response)
            this.list.unshift(this.addData)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleOpenMap(row) {
      this.dialogMapVisible = true
    },
    handleRedirectToImage(id) {
      router.push({ path: 'image/list', query: { id: id }})
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除 ' + row.cn_name + ' ?')
        .then(_ => {
          moduleDel(row.id).then((response) => {
            this.$notify({
              title: '处理成功',
              message: '删除 ' + row.cn_name + ' 成功!',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(_ => {
        })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 选择省份和城市触发
    handleCityChange(value) {
      const provinceId = value[0]
      const cityId = value[1]
      this.addData.province_id = provinceId
      this.addData.city_id = cityId
    },
    // 选择省份和城市触发
    handleSearchCityChange(value) {
      const provinceId = value[0]
      const cityId = value[1]
      this.searchData.provinceId = provinceId
      this.searchData.cityId = cityId
    }
  }
}
</script>
